/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
/*
 * Topology Viewer
 */

package cgl.narada.topology.viewer;

import java.awt.Color;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * This class managed all the links present in the system.
 */
public class LinkManagement {
    
    public List links;
    /**
     * maintains the count of links present in the system.
     */
    private int linkCount;
    
    /**
     * Only constructor. Initialises link count.
     */
    public LinkManagement() {
	links = new ArrayList();
	linkCount = 0;
    }

    /**
     * Adds a link between the specified node pair. Increments the linkCount.
     * @param n1 one end <code>Noed</code> of a link. 
     * @param n2 other end <code>node</code> of a link.
     * @param linkId id of a link to be inserted.
     * @param linkType type of a link to be inserted.
     */
    public void addLink(Node n1, Node n2, int linkId, String linkType) {
	// first check if the pair of nodes is present in the list
	LinkDetails link = getLinkDetails(n1, n2);
	if (link == null) {
	    // first insert the new LinkDetails record
	    link = new LinkDetails(n1, n2);
	    link.linkColor = getLinkColor(n1, n2);
	    links.add(link);
	}
	link.insertLinkForNode(linkId, linkType);
	linkCount++;
    }

    /**
     * Deletes a particular link between two nodes.
     * @param n1 one end <code>Noed</code> of a link. 
     * @param n2 other end <code>node</code> of a link.
     * @param linkId id of the link to be deleted.
     * @throws TopologyException if specified node pair is not found.
     */
    public void deleteLink(Node n1, Node n2, int linkId) 
	throws TopologyException{
	LinkDetails link = getLinkDetails(n1, n2);
	if (link == null) {
	    throw new TopologyException("Node pair not present while"
				       + "deleting the link");
	} else {
	    link.deleteLinkForNode(linkId);
	}
	if (link.linksForOneNode.isEmpty()) {
	    boolean linkRemoved = links.remove(link);
	}
	linkCount--;
    }

    /**
     * Deletes all the links emerging from the specified node.
     * @param n <code>Node</code> whose connections are being removed.
     */
    public void deleteAllLinksForNode(Node n) {
	Iterator it = links.iterator();
	while (it.hasNext()) {
	    LinkDetails link = (LinkDetails) it.next();
	    if ((link.connectedNode1 == n) || (link.connectedNode2 == n)) {
		int numLinksDeleted = link.deleteAllLinksForNode();
		it.remove();
		linkCount = linkCount - numLinksDeleted;
	    }
	}
    }
    
    public void deleteLinksForPair(Node n1, Node n2) {
	LinkDetails link = getLinkDetails(n1, n2);
	int numLinksDeleted = link.deleteAllLinksForNode();
	linkCount = linkCount - numLinksDeleted;
	if (links.remove(link)) {
	    //System.out.println("Links between pair, successfully removed");
	}
    }

    public void deleteAllLinks() {
	Iterator it = links.iterator();
	while (it.hasNext()) {
	    LinkDetails link = (LinkDetails) it.next();
	    link.deleteAllLinksForNode();
	    it.remove();
	}
    }

    /**
     * Returns total number of links present in the system.
     * @return linkCount total link count.
     */
    public int getLinkCount() {
	return linkCount;
    }

    /**
     * Returns all the links emerging from a particular node.
     * @param n <code>Node</code> of which connections are being returned.
     * @return <code>List</code> of all the links emerging from specified node.
     */
    public List getAllLinksForNode(Node n) {
	List allLinks = new ArrayList();
	Iterator it1 = links.iterator();
	while (it1.hasNext()) {
	    LinkDetails link = (LinkDetails) it1.next();
	    if ((link.connectedNode1 == n) || (link.connectedNode2 == n)) {
		List linksForSingleNode = link.getAllLinksForNode();
		Iterator it2 = linksForSingleNode.iterator();
		while (it2.hasNext()) {
		    String individualLink = 
			((link.connectedNode1 == n) 
			 ? link.connectedNode2.getNodeAddress()
			 : link.connectedNode1.getNodeAddress()) 
			+ ", " + (String) it2.next();
		    allLinks.add(individualLink);
		}
	    }
	}
	Collections.sort(allLinks);
	return allLinks;
    }

    /**
     * Returns all the links between a given node pair.
     * @param  n1 one <code>Node</code> of a pair.
     * @param  n2 other <code>Node</code> of a pair.
     * @return <code>List</code> containing <code>String</code> representations
     *         of all the links between specified pair.
     */
    public List getAllLinksForPair(Node n1, Node n2) {
	List allLinks = new ArrayList();
	Iterator it1 = links.iterator();
	while ((it1.hasNext()) && (allLinks.isEmpty())) {
	    LinkDetails link = (LinkDetails) it1.next();
	    if (((link.connectedNode1 == n1) && (link.connectedNode2 == n2)) 
		|| ((link.connectedNode1 == n2) 
		    && (link.connectedNode2 == n1))) {
		List linksForNodePair = link.getAllLinksForNode();
		Iterator it2 = linksForNodePair.iterator();
		while (it2.hasNext()) {
		    String individualLink = (String) it2.next();
		    allLinks.add(individualLink);
		}
	    }
	}
	Collections.sort(allLinks);
	return allLinks;
    }
		
    /**
     * Get object containing information about all the links between specified
     * node pair.
     * @param  n1 one end <code>Node</code> of a link.
     * @param  n2 other end <code>Node</code> of a link.
     * @return <code>LinkDetails</code> object for a specified node pair.
     */
    public LinkDetails getLinkDetails(Node n1, Node n2) {
	Iterator it = links.iterator();
	while (it.hasNext()) {
	    LinkDetails l = (LinkDetails) it.next();
	    if (((l.connectedNode1 == n1) && (l.connectedNode2 == n2))
		|| ((l.connectedNode1 == n2) && (l.connectedNode2 == n1))) {
		return l;
	    }
	}
	return null;
    }

    /**
     * Draws all the links present in the system.
     * @param g <code>Graphics</code> object pertaining to the image being 
     *        drawn.
     */
     public void drawAllLinks(Graphics g) {
	Iterator it1 = links.iterator();
	while (it1.hasNext()) {
	    LinkDetails link = (LinkDetails) it1.next();
	    Iterator it2 = link.linksForOneNode.iterator();
	    while (it2.hasNext()) {
		Link l = (Link) it2.next();
		g.setColor(link.linkColor);
		g.drawLine((int) link.connectedNode1.nodeLocation.getCenterX(),
			   (int) link.connectedNode1.nodeLocation.getCenterY(),
			   (int) link.connectedNode2.nodeLocation.getCenterX(),
			   (int) link.connectedNode2.nodeLocation.getCenterY());
	    }
	}
    }

    /**
     * Gets one of the four colors depending upon the end nodes of a link
     * @param  n1 one end <code>Node</code> of a link.
     * @param  n2 other end <code>Node</code> of a link.
     * @return <code>Color</code> object for the link between specified node 
     *         pair.
     */
    public Color getLinkColor(Node n1, Node n2) {
	if (n1.parentSSClusterId == n2.parentSSClusterId) {
	    if (n1.parentSClusterId == n2.parentSClusterId) {
		if (n1.parentClusterId == n2.parentClusterId) {
		    return new Color(242, 0, 72);
		} else {
		    return new Color(10, 138, 83);
		}
	    } else {
		return new Color(180, 95, 0);
	    }
	} else {
	    return new Color(50, 50, 116);
	}
    }

};
